package com.lqq.action;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import com.lqq.biz.AdminBiz;
import com.lqq.biz.FoodAndFoodTypeBiz;
import com.lqq.biz.FoodBiz;
import com.lqq.biz.FoodTypeBiz;
import com.lqq.biz.OrderMainBiz;
import com.lqq.entity.Admins;
import com.lqq.entity.FoodTypes;
import com.lqq.entity.Foods;
import com.lqq.entity.Orders;
import com.lqq.entity.Pager;
import com.opensymphony.xwork2.ActionSupport;

public class AdminAction extends ActionSupport implements RequestAware,SessionAware,ServletResponseAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	AdminBiz adminBiz;

	public void setAdminBiz(AdminBiz adminBiz) {
		this.adminBiz = adminBiz;
	}

	Map<String, Object> request;
	@Override
	public void setRequest(Map<String, Object> arg0) {
		// TODO Auto-generated method stub
		this.request = arg0;
	}
	
	Map<String, Object> sessionMap;
	@Override
	public void setSession(Map<String, Object> arg0) {
		// TODO Auto-generated method stub
		this.sessionMap = arg0;
	}
	
	private Admins admin;
	public Admins getAdmin() {
		return admin;
	}
	public void setAdmin(Admins admin) {
		this.admin = admin;
	}

	public String login() {
		if(admin.getLoginName() == null ||admin.getLoginName().equals("") || admin.getLoginPassword() == null || admin.getLoginPassword().equals("")){
			addActionError("用户名或密码不能为空!");
			return INPUT;
		}
		if(adminBiz.check_login(admin)){
			sessionMap.put("admin", admin);
			return SUCCESS;
			
		}else{
			addActionError("用户名或密码有误!");
			return INPUT;
		}
		
	}
	public String layerLogin() throws IOException{
		if(adminBiz.check_login(admin)){
			sessionMap.put("admin", admin);
			response.getWriter().write("OK");
			return null;
		}else{
			response.getWriter().write("ERROR_USER");
			return null;
		}
	}
	
	private Pager pager;
	private Integer foodTypeId;
	private Foods food;
	FoodBiz foodBiz;
	FoodTypeBiz foodTypeBiz;

	private String foodName;
	public String getFoodName() {
		return foodName;
	}
	public void setFoodName(String foodName) {
		this.foodName = foodName;
	}
	public void setFoodTypeBiz(FoodTypeBiz foodTypeBiz) {
		this.foodTypeBiz = foodTypeBiz;
	}
	public void setFoodBiz(FoodBiz foodBiz) {
		this.foodBiz = foodBiz;
	}
	public Pager getPager() {
		return pager;
	}
	public void setPager(Pager pager) {
		this.pager = pager;
	}
	public Integer getFoodTypeId() {
		return foodTypeId;
	}
	public void setFoodTypeId(Integer foodTypeId) {
		this.foodTypeId = foodTypeId;
	}
	public Foods getFood() {
		return food;
	}
	public void setFood(Foods food) {
		this.food = food;
	}
	public String index(){
		
		int curPage = 1;
		int pageSize = 2;
		
		if(pager != null){
			curPage = pager.getCurPage();
		}
		
		List<Foods> foodsList = null;
		if(foodTypeId != null){
			
			foodsList = foodBiz.getFoodsByPagerAndType(foodTypeId, curPage, pageSize);
			pager = foodBiz.getPagerByFoodType(foodTypeId, pageSize);
		}else{
			foodsList = foodBiz.getFoodsByPager(curPage, pageSize);
			pager = foodBiz.getFoodPager(pageSize);
		}
		pager.setCurPage(curPage);
		request.put("foodList", foodsList);
		getFoodTypesList();
		return SUCCESS;
	}
	
	public String search() throws UnsupportedEncodingException{
		int curPage = 1;
		int pageSize = 2;
		if(pager != null){
			curPage = pager.getCurPage();
		}
		List<Foods> foodList = null;
		if(!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode(foodName))){
			foodName = new String(foodName.getBytes("ISO-8859-1"),"UTF-8");
		}
		foodList = foodBiz.getFoodsByPagerAndName(foodName, curPage, pageSize);
		pager = foodBiz.getPagerByFoodName(foodName, pageSize);
		pager.setCurPage(curPage);
		
		request.put("foodList", foodList);
		getFoodTypesList();
		return SUCCESS;
	}
	
	public String addUser() throws IOException{

		if(adminBiz.loginNameIsExist(admin.getLoginName())){
			response.getWriter().write("FALSE");
			return null;
		}
		adminBiz.add(admin);
		response.getWriter().write("OK");
		
		return null;
	}
	
	//��Ӳ�Ʒ
	
	private File doc;
	private String docFileName;
	private String docContentType;
	
	public String preAddFood(){
		
		getFoodTypesListFromSession();
		return SUCCESS;
		
	}
	private void getFoodTypesListFromSession() {
		// TODO Auto-generated method stub
		List<FoodTypes> list = foodTypeBiz.getAllFoodTypes();
		sessionMap.put("foodTypeList", list);
	}
	public String addFood() throws IOException{
		if(docFileName != null){
			String targetPath = ServletActionContext.getServletContext().getRealPath("/food-images");
			String targetFileName = generateFileName(docFileName);
			File target = new File(targetPath,targetFileName);
			FileUtils.copyFile(doc, target);
			FoodTypes types = foodTypeBiz.getFoodTypeByFoodTypeId(foodTypeId);
			types.getFoods().add(food);
			food.setFoodImage(targetFileName);
			foodBiz.add(food);
			foodTypeBiz.update(types);
			return SUCCESS;
		}
		addActionError("文件名不能为空!");
		return INPUT;
	}
	private String generateFileName(String fileName){
		
		String formatDate = new SimpleDateFormat("yyMMddHHmmss").format(new Date());
		int randow = new Random().nextInt(10000);
		int position = fileName.lastIndexOf(".");
		String extension = fileName.substring(position);
		return formatDate + randow + extension;
	}
	
	//ɾ����Ʒ
	private Integer foodId;
	
	public Integer getFoodId() {
		return foodId;
	}
	public void setFoodId(Integer foodId) {
		this.foodId = foodId;
	}
	public String deleteFood() throws IOException{
		
		food = foodBiz.getFoodById(food.getFoodId());
		Set<FoodTypes> typeList = food.getFoodTypes();
		for(FoodTypes types : typeList){
			int typeId = types.getFoodTypeId();
			foodAndFoodTypeBiz.deleteByFoodIdAndFoodTypeId(food.getFoodId(),typeId);
		}
		
		try {
			foodBiz.delete(food);
			response.getWriter().write("OK");
			return null;
		} catch (Exception e) {
			for(FoodTypes types : typeList){
				Foods food2 = foodBiz.getFoodById(food.getFoodId());
				types.getFoods().add(food2);
				foodTypeBiz.update(types);
			}
			response.getWriter().write("FALSE");
			return null;
			// TODO: handle exception
		}
	}
	
	public String preEditFood(){
		getFoodTypesListFromSession();
		food = foodBiz.getFoodById(food.getFoodId());
		return SUCCESS;
	}
	
	FoodAndFoodTypeBiz foodAndFoodTypeBiz;
	
	public void setFoodAndFoodTypeBiz(FoodAndFoodTypeBiz foodAndFoodTypeBiz) {
		this.foodAndFoodTypeBiz = foodAndFoodTypeBiz;
	}
	public String editFood() throws IOException{

		Foods tmp_food = foodBiz.getFoodById(food.getFoodId());
		boolean result = false;
		for(FoodTypes type : tmp_food.getFoodTypes()){
			if(type.getFoodTypeId() == foodTypeId){
				result = true;
				break;
			}
		}
		if(docFileName != null){
			String targetPath = ServletActionContext.getServletContext().getRealPath("/food-images");
			String targetFileName = generateFileName(docFileName);
			File target = new File(targetPath,targetFileName);
			FileUtils.copyFile(doc, target);
			food.setFoodImage(targetFileName);
			foodBiz.update(food);
		}else{
			food.setFoodImage(tmp_food.getFoodImage());
			foodBiz.update(food);
		}
		if(!result){
			FoodTypes foodTypes = foodTypeBiz.getFoodTypeByFoodTypeId(foodTypeId);
			for(FoodTypes type : tmp_food.getFoodTypes()){
				foodAndFoodTypeBiz.deleteByFoodIdAndFoodTypeId(food.getFoodId(), type.getFoodTypeId());
			}
			foodTypes.getFoods().add(food);
			foodTypeBiz.update(foodTypes);
		}
		return SUCCESS;
		
	}
	
	OrderMainBiz orderMainBiz;
	
	public void setOrderMainBiz(OrderMainBiz orderMainBiz) {
		this.orderMainBiz = orderMainBiz;
	}
	private Orders orders;
	public Orders getOrders() {
		return orders;
	}
	public void setOrders(Orders orders) {
		this.orders = orders;
	}
	private Integer orderId;
	
	public Integer getOrderId() {
		return orderId;
	}
	public void setOrderId(Integer orderId) {
		this.orderId = orderId;
	}
	//��������
	public String preDoOrder(){
		
		int curPage = 1;
		int pageSize = 10;
		if(pager != null){
			curPage = pager.getCurPage();
		}
		List<Orders> list = null;
		list = orderMainBiz.getAllOrdersByPager(curPage, pageSize);
		pager = orderMainBiz.getPager(pageSize);
		pager.setCurPage(curPage);
		request.put("orderList", list);
		return SUCCESS;
		
	}
	public String searchOrder(){
		int curPage = 1;
		int pageSize = 10;
		if(pager != null){
			curPage = pager.getCurPage();
		}
		if(userName != null){
			Set<Orders> list = orderMainBiz.getOrdersByUserAndOrderState(userName, orderState);
			pager = new Pager();
			pager.setRowCount(orderMainBiz.getCountOfOrdersByUserAndOrderState(userName, orderState));
			pager.setPageSize(1000);
			pager.setCurPage(curPage);
			request.put("orderList", list);
			return SUCCESS;
		}else{
			List<Orders> list = orderMainBiz.getOrderByOrderIdAndState(curPage, pageSize, orderId, orderState);
			pager = orderMainBiz.getPagerByOrderIdAndState(pageSize, orderId, orderState);
			pager.setCurPage(curPage);
			request.put("orderList", list);
			return SUCCESS;
		}
		
	}
	
	private String orderState;
	private String userName;
	
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getOrderState() {
		return orderState;
	}
	public void setOrderState(String orderState) {
		this.orderState = orderState;
	}
	public String doOrder() throws IOException{
		orders = orderMainBiz.getOrderByOrderId(orderId);
		orders.setOrderState(orderState);
		orderMainBiz.update(orders);
		response.getWriter().write("OK");
		return null;
	}
	
	public String logout(){
		sessionMap.clear();
		return SUCCESS;
	}
	
	public File getDoc() {
		return doc;
	}
	public void setDoc(File doc) {
		this.doc = doc;
	}
	public String getDocFileName() {
		return docFileName;
	}
	public void setDocFileName(String docFileName) {
		this.docFileName = docFileName;
	}
	public String getDocContentType() {
		return docContentType;
	}
	public void setDocContentType(String docContentType) {
		this.docContentType = docContentType;
	}
	private void getFoodTypesList() {
		// TODO Auto-generated method stub
		List<FoodTypes> list = foodTypeBiz.getAllFoodTypes();
		request.put("foodTypeList", list);
	}

	HttpServletResponse response;
	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		// TODO Auto-generated method stub
		this.response = arg0;
	}

}
